package com.game.sdk.screen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.game.sdk.util.Logger;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Environment;
import android.util.Log;
import android.view.View;

public class ShotScreen {
	private static final String TAG = "shotscreen";
	private static String FILE_CACHE_DIR = "/huosdk/shotscreen";

	public static Bitmap takeScreenShot(Activity activity) {
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		Rect rect = new Rect();
		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
		int statusBarHeight = rect.top;
		System.out.println(statusBarHeight);

		int width = activity.getWindowManager().getDefaultDisplay().getWidth();
		int height = activity.getWindowManager().getDefaultDisplay()
				.getHeight();

		Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width,
				height - statusBarHeight);
		view.destroyDrawingCache();
		return bitmap2;
	}

	private static void savePic(Bitmap bitmap, String filename) {
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(filename);
			if (fileOutputStream != null) {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 90,
						fileOutputStream);
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		} catch (FileNotFoundException e) {
			Logger.msg("Exception:FileNotFoundException");
			e.printStackTrace();
		} catch (IOException e) {
			Logger.msg("IOException:IOException");
			e.printStackTrace();
		}
	}

	public static void shoot(Activity a) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			FILE_CACHE_DIR = Environment.getExternalStoragePublicDirectory(
					Environment.DIRECTORY_DCIM).getAbsolutePath();
		} else {
			FILE_CACHE_DIR = "/data/data/" + a.getPackageName()
					+ FILE_CACHE_DIR;
		}
		File file = new File(FILE_CACHE_DIR);
		if (!file.exists()) {
			file.mkdirs();
		}
		File fileImag = new File(FILE_CACHE_DIR + "/" + "账号密码.jgp");
		try {
			if (!fileImag.exists())
				fileImag.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ShotScreen.savePic(ShotScreen.takeScreenShot(a),
				fileImag.getAbsolutePath());
	}
}
